package com.atm.servlet;

import com.atm.pojo.RunMessage;
import com.atm.pojo.User;
import com.atm.service.RunMessageService;
import com.atm.service.UserService;
import com.atm.service.impl.RunMessageServiceImpl;
import com.atm.service.impl.UserServiceImpl;
import com.atm.utill.MailUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 用户存款
 */
@WebServlet("/UserStore")
public class UserStoreServlet extends HttpServlet {
    private UserService userService=new UserServiceImpl();
    private RunMessageService runMessageService=new RunMessageServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String saveNum = req.getParameter("saveNum");
        String icno = null;
        if (req.getSession().getAttribute("ua")!=null){
            User user=(User)req.getSession().getAttribute("ua");
            icno = user.getIcno();
        }
        int money=0;
        if (saveNum != null){
            money=Integer.parseInt(saveNum);
        }
        if (money==0){
            req.getSession().setAttribute("error3","存款不能为0");
            resp.sendRedirect("/changepage/UserStore.jsp");
        }else if (money>2000){
            req.getSession().setAttribute("error3","存款不能大于2000");
            resp.sendRedirect("/changepage/UserStore.jsp");
        }else if (money%50!=0){
            req.getSession().setAttribute("error3","存款为50的倍数");
            resp.sendRedirect("/changepage/UserStore.jsp");
        }else {
            boolean result=userService.saveMoney(money,icno);
            //保存交易记录
            RunMessage runMessage = new RunMessage();
            runMessage.setIcno(icno);
            Date date = new Date();
            runMessage.setRm_date(new Date().toString());
            runMessage.setRm_balance(Double.parseDouble(String.valueOf(money)));
            runMessage.setRm_rest(userService.getUserBalance(icno));
            runMessage.setRm_currency("RMB");
            runMessageService.addRunMessage(runMessage);
            if (result){
                double userBalance = userService.getUserBalance(icno);
                String email = userService.getEmailByIcno(icno);
                String content="您的卡号为:"+icno+" 的账户存款"+money+"\n 剩余金额为:"+userBalance;
                MailUtils.sendEmail(email,"ATM模拟系统存款",content);
                resp.sendRedirect("/UserSerch");
            }
        }
    }
}
